$(function(){
    // 提交按钮点击事件
    $(document).on("click","#sub",function(){
        var $comment = $('#commentarea').val();
		var $username = $('#username').val();
        console.log($comment);
		if($comment&&$username != ""){
			SendComment($comment, $username);
			$('.commentm').hide();
			$('.usernamem').hide();
		}else if($comment == "" && $username != ""){
			$('.commentm').show();
			$('#commentarea').focus();
			return false;
		}else if($comment != "" && $username == ""){
			$('.usernamem').show();
			$('#username').focus();
			return false;
		}else{			
			$('.commentm').show();
			$('.usernamem').show();
			alert("留言输入错误！");
			return false;
		}
    });
});
function SendComment(comment, name){
	var $usercomment = "<b><i>" + name + "</i></b>" + "&nbsp;&nbsp;发表于&nbsp;&nbsp;"
						+ "<i>" + GetDate() + "</i>" + "<br />" + comment + "<br />";
	var $commentslist = $('#comments').html() + $usercomment;
	$.ajax({
		url: "",
		// cache: false,
		// crossDomain: false,
		// 未加dataType时，jQuery1.9.1之前的版本可以执行success，之后版本只执行error
		// 加上dataType后jQuery1.9.1之后的版本不再执行error而是正常执行success，
		// 但是ajaxStart和ajaxStop没有执行
		dataType: 'text',
		data: "&comment=&d=" + new Date() + "&commentslist=" + $commentslist,
		success: function(data){
			$('#comments').html($commentslist);
			$('#comments').get(0).scrollTop = $('#comments').get(0).scrollHeight;
            $('#commentarea').html("");
            $("#commentName").text(name);
            $("#commentText").text(comment);
		},
		error: function(){
			alert("留言提交失败！");
		}
	});
}
function GetDate(){
	var t = new Date();
	var y = t.getFullYear();
	var m = t.getMonth() + 1;
	var d = t.getDate();
	var h = t.getHours();
	var min = t.getMinutes();
	var s = t.getSeconds();
	var time = y + "/" + m + "/" + d + "&nbsp;&nbsp;" + h + ":" + min + ":" + s;
	return time;
}